package com.example.demo;

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.extension.annotations.SpanAttribute;
import io.opentelemetry.extension.annotations.WithSpan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Service1Application {

    private Logger logger = LoggerFactory.getLogger(Service1Application.class);

    public static void main(String[] args) {

//        try {
//            System.out.println("故障注入开始。。。。。");
//            Thread.sleep(10000000);
//            System.out.println("故障注入结束。。。。。");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        SpringApplication.run(Service1Application.class, args);
    }

    @GetMapping({"/", "/index"})
    public String index() {
        logger.info("hello service1.");
        return "hello service1.";
    }

    @GetMapping({"/result/{requestId}"})
    @WithSpan
    public R<Object> result(@SpanAttribute("requestId") @PathVariable("requestId") String requestId) {
        logger.info("hello service1.");

        Span span = Span.current();
        span.setAttribute("mySpan1", "111111");
        span.setAttribute("mySpan2", "111111");
        span.setAttribute("mySpan3", "111111");
        span.setAttribute("mySpan4", "111111");

        return R.ok(new HashMap<String, String>() {
            {
                put("mySpan", "111111");
                put("result", "执行成功！");
                put("requestId", requestId);
            }
        }, "Success");
    }

    @RequestMapping(value = "/getService2")
    public String getService2() throws Exception {
        String result = getRequest("http://localhost:8082/");
        return result;
    }

    @RequestMapping(value = "/getService3")
    public String getService3() throws Exception {
        Span span = Span.current();
        span.setAttribute("requestId", "999999");

        String result = getRequest("http://localhost:8082/getService3");
        return result;
    }

    /**
     * @param url：http接口地址
     * @param param：传入参数，格式为?param1=xxx&param2=xxx，如果值xxx含有特殊字符，可以用param = "image=" + URLEncoder.encode(image,"utf-8");
     * @throws Exception
     * @return: 返回调用接口得到的json字符串（是否为json字符串决定于http接口），是json字符串则可以进行相应解析，Map<String,Object> moodRes = (Map<String,Object>)JSONObject.parse(result)
     */
    public static String postRequest(String url, String param) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String getRequest(String url) throws Exception {
        String message = "";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

            http.connect();

            InputStream is = http.getInputStream();
            int size = is.available();

            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }
}
